var form = layui.form, laydate = layui.laydate, annexList = [], upload = layui.upload, table = layui.table, $ = layui.jquery,
    id = getQueryVariable("id");
layui.use(['tableEdit'], function () {
    let  tableEdit = layui.tableEdit;
    let layer = layui.layer;

    lay('.starttime').each(function(){
        laydate.render({
            elem: this
        });
    });

    let detailData = [];
    let operationLog = [];
    layer.ready(function () {
        //获取详情信息
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:JSON.stringify(id),
            url:"inventory/update",
            success:function(res){
                if(res.status == 200){
                    //主表信息赋值
                    $("#billNo").val(res.data.billNo);
                    $("#newBillNo").val(res.data.billNo);
                    $("#operationDate").val(res.data.operationDate);
                    let managerCode = res.data.managerCode;
                    $("#creator").val(res.data.creator);
                    $("#memo").val(res.data.memo);

                    //产品列表信息
                    detailData = res.data.detailVos;

                    //附件信息
                    annexList = res.data.annexVos;

                    table.reload('storageproductstableid',{data : detailData});
                    table.reload('attachmenttableid',{data : annexList});

                    //获取所有用户信息
                    $.ajax({
                        url:"otherOutStock/getAllUserInfo",
                        success:function(data){
                            if(data.status == 200){
                                for(let i in data.data){
                                    $("#managerCode").append("<option value=\"" + data.data[i].code + "\">" + data.data[i].name + "</option>");
                                }
                                let selectUser = 'dd[lay-value=' + managerCode + ']';
                                $('#managerCode').siblings("div.layui-form-select").find('dl').find(selectUser).click();
                                $("#manager").val(res.data.name);
                                form.render('select');
                            }
                        }
                    });
                    return false;
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    })


//表单初始值，修改时调用
    if (id != "") {
        form.val("editor-form", {
            "inventorynumber": "盘点单号",
        })
    }

//监听提交
    form.on('submit(form-element)', function (data) {
        //向后台组装数据
        //获取头部表单数据
        let req = data.field;
        //获取附件数据
        let annexReqs = table.cache["attachmenttableid"];
        //获取库存表单信息数据
        let transferDetails = table.cache["storageproductstableid"];
        if(transferDetails.length > 0){
            for(let i in transferDetails){
                if(null == transferDetails[i].realInventoryNum || transferDetails[i].realInventoryNum <= 0){
                    layer.confirm("存在实盘数量为零的记录，这些记录提交后不会生成相关记录，是否删除？",
                        confirmInfo(3,6),
                        function (index) {
                            let newData = deleteTransferData(transferDetails);
                            table.reload('storageproductstableid',{data : newData});
                            layer.close(index);
                        });
                    return false;
                }
            }
        }

        req["annexList"] = annexReqs;
        req["details"] = transferDetails;
        let datas = JSON.stringify(req);
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:datas,
            url:"inventory/add",
            success:function(res){
                if(res.status == 200){
                    layer.msg("保存成功", {icon: 6});
                    setTimeout(function () {
                        //保存成功则刷新提交过来的界面 并关闭此页面
                        parent.detab("views/jsp/WarehouseManagement/inventory.jsp");
                        parent.intab("views/jsp/WarehouseManagement/inventory.jsp","盘点")
                        parent.detab("views/jsp/WarehouseManagement/tpl/newupinventory.jsp"+(id==''?'':'?id='+id));
                    },1000)
                    return false;
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    });

    //遍历删除实盘数量为0的数据
    function deleteTransferData(transferDetails){
        for(var j = 0; j < transferDetails.length; j++){
            if(transferDetails[j].realInventoryNum <= 0){
                transferDetails.splice(j, 1);
                j--;
            }
        }
        return transferDetails;
    }


//--库存产品信息
    var cols = table.render({
        elem: '#storageproducts',
        id: 'storageproductstableid',
        data: detailData,
        toolbar: '#storageproductstoolbar',
        cols: [[
            {field: 'warehouseIdStr',width: 120,title: '仓库'},
            {field: 'productCode', width: 120, title: '产品编码', sort: true},
            {field: 'specificationCode', width: 120, title: '规格编码', sort: true},
            {field: 'lotNo', width: 100, title: '批次号'},
            {field: 'specificationExplanation', width: 120, title: '规格说明'},
            {field: 'copyStockNum', width: 120, title: '抄库数量', sort: true},
            {field: 'realInventoryNum', width: 120, title: '实盘数量',event: 'realInventoryNum',"config":{"type":"input","verify":{"type":"number"}}},
            {field: 'profitLossNum', width: 120, title: '盈亏数量'},
            {field: 'costUnitPrice', width: 120, title: '成本单价'},
            {field: 'productUnit', width: 120, title: '单位'},
            {field: 'clientProductNo', width: 120, title: '客户货号'},
            {field: 'productCname', width: 120, title: '中文名称'},
            {field: 'productEname', width: 120, title: '英文名称'},
            {field: 'productCdesc', width: 120, title: '中文描述'},
            {field: 'productEdesc', width: 120, title: '英文描述'},
            {field: 'color', width: 120, title: '颜色'},
            {field: 'trayNumber', width: 120, title: '托盘入数'},
            {field: 'totalTray', width: 120, title: '总托盘'},
            {field: 'profitLossMoney', width: 120, title: '盈亏金额'},
            {fixed: 'right', title: '操作', width: 110, align: 'center', toolbar: '#storageproductseditor'}]],
        page: true,
        height: 380
    }).config.cols;
    var aopTable = tableEdit.aopObj(cols); //获取一个aop对象
    aopTable.on('tool(storageproductstable)', function (obj) {
        let field = $(this).data('field');
        let data = obj.data;
        if (field === 'realInventoryNum') {
            if(!checkInventoryQuantity(obj.val(), data.canInventoryLeastNum)){
                layer.msg("实盘数量不能小于最低盘点数量", {icon: 5});
                return;
            }
            obj.update({"realInventoryNum": obj.value});
            layer.msg("修改成功", {icon: 6});
        }
        if (obj.event === 'del') {
            if(data.deleteFlag){
                layer.confirm('确认删除?', confirmInfo(3, 5), function (index) {
                    let oldData =  table.cache["storageproductstableid"];
                    for (var i = 0; i < oldData.length; i++) {
                        if (oldData[i].stockId == obj.data.stockId) {
                            oldData.splice(i, 1);
                            i--;
                            table.reload('storageproductstableid',{data : oldData});
                            break;
                        }
                    }
                    layer.msg("删除成功", {icon: 6});
                    layer.close(index);
                });
            }else{
                layer.msg("该数据不能删除", {icon: 5});
            }
        }
    });

    table.on('toolbar(storageproductstable)', function (obj) {
        switch (obj.event) {
            case 'inventoryproducts':
                layer.open({
                    type: 2,
                    area:["80%","95%"],
                    content: 'views/jsp/WarehouseManagement/tpl/inventory_inventoryproducts.jsp'
                });
                break;
        };
    });

    //数据校验
    //实盘数量不能小于最少实盘数量
    function checkInventoryQuantity(realInventoryNum, canInventoryLeastNum){
        if(realInventoryNum < canInventoryLeastNum){
            return false;
        }
        return true;
    }

    //---附件
    table.render({
        elem: '#attachment'
        , data: annexList
        , toolbar: '#attachmenttoolbar'
        , cols: [[
            {field: 'fileName', title: '文件名', fixed: true}
            , {field: 'uploadTime', title: '上传日期', fixed: true}
            , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: true
        , done: function (res, index, upload) {
            let data = res.data;
            for(let i in data){
                let flag = true;
                for(let j in annexList){
                    if(data[i].id == annexList[j].id){
                        flag = false;
                        break;
                    }
                }
                if(flag){
                    annexList.push(data[i]);
                }
            }
        }
    });
    upload.render({
        elem: '#uploadfile'
        , url: 'transfer/uploadFile'
        , field: "uploadify"
        , accept: 'file'
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                $("#uploadlist").append(tr);
            });
        }
        , parseData: function(res){
            return {
                "code": res.status,
                "count": res.total,
                "data": res.data
            };
        }
        , done: function (res, index, upload) {
            let data = res.data;
            for(var i in data){
                if (data[i].status) { //上传成功
                    annexList.push(data[i]);
                    var tr = $("#uploadlist").find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(3).html(''); //清空操作
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
        }
        , error: function (index, upload) {
            var tr = $("#uploadlist").find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                    }
                });
                break;
        }
        ;
    });
    table.on('tool(attachmenttable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            let xmlHttpRequest = new XMLHttpRequest();
            let url = "wjinfo/downloadfile2?filename=" + data.filePath;
            xmlHttpRequest.open('GET', url, true);
            //设置请求头
            xmlHttpRequest.setRequestHeader("Content-type", "application/json")
            xmlHttpRequest.responseType = "blob";
            xmlHttpRequest.send(null);

            xmlHttpRequest.onload = function() {
                let content = xmlHttpRequest.response;
                // 组装a标签
                let elink = document.createElement("a");

                //设置文件下载路径
                elink.download = decodeURIComponent(data.fileName);
                elink.style.display = "none";
                let blob = new Blob([content], { type: 'application/force-download' });

                //解决下载不存在文件的问题，根据blob大小判断
                if(blob.size==0){
                    layer.msg('服务器没找到此文件，请联系管理员!');
                }else{
                    elink.href = window.URL.createObjectURL(blob);
                    document.body.appendChild(elink);
                    elink.click();
                    document.body.removeChild(elink);
                }

            }
        } else if (obj.event === 'del') {
            layer.confirm('确认删除?',
                confirmInfo(3,5), function (index) {
                    obj.del();
                    let id = data.id;
                    for (var i = 0; i < annexList.length; i++) {
                        if (annexList[i].id == id) {
                            annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                            i--; // 如果不减，将漏掉一个元素
                            break;
                        }
                    }
                    layer.msg("删除成功", {icon: 6});
                    layer.close(index);
                    table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
                });
        }
    });

//---操作日志
    table.render({
        elem: '#otherwarehouselog'
        , data: operationLog
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });

    //时间处理 初始赋值
    function getNowFormatDate() {
        let date = new Date();
        let separator = "-";
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        let currentDate = year + separator + month + separator + strDate;
        return currentDate;
    }
    let currentDate = getNowFormatDate();
    /*//盘点时间
    laydate.render({
        elem: '#operationDate',
        value: currentDate,
        isInitValue: true
    });*/

    //创建时间
    laydate.render({
        elem: '#createDate',
        value: currentDate,
        min: currentDate,
        max: currentDate,
        btns: ['confirm']
    });


    //提示信息渲染
    function confirmInfo(icon, anim) {
        let data = {
            icon: icon,
            title: "提示",
            offset: "auto",
            skin: 'layui-layer-molv',
            anim: anim
        }
        return data;
    }
})